#!/bin/sh

PROGNAME="docker_setup.sh"

# 检查是否是 root 用户运行，安装软件需要使用 root 用户权限
if sudo -v &>/dev/null;
then
	echo $(whoami) is sudo user;
else
	echo $(whoami) is not sudo user;
fi

# 目录设置
ROOT_DIR=$(cd $(dirname $0); pwd)
SCRIPTS_DIR=${ROOT_DIR}/scripts
TOOLS_DIR=${ROOT_DIR}/tools

# 文件设置
UBUNTU_DEFAULT_IMAGE=imagebuilder:xx.xx
UBUNTU_1804_IMAGE=imagebuilder:18.04
UBUNTU_2204_IMAGE=imagebuilder:22.04
UBUNTU_DEFAULT_IMAGE_BUILD_FILE=imagebuilder-xx.xx.dockerfile
UBUNTU_1804_IMAGE_BUILD_FILE=imagebuilder-18.04.dockerfile
UBUNTU_2204_IMAGE_BUILD_FILE=imagebuilder-22.04.dockerfile

uninstall_software()
{
    # 停止并删除 docker 镜像
    docker image prune --force --all
    docker container prune -f

    # 卸载旧版本的软件
    apt-get remove docker docker-engine docker.io containerd runc
    apt-get purge docker-ce docker-ce-cli containerd.io docker-compose-plugin
    rm -rf /var/lib/docker
    rm -rf /var/lib/containerd

    if [ -d "/etc/apt/keyrings/" ]; then
        rm -rf /etc/apt/keyrings
    fi
}

install_software()
{
    apt-get update
    apt-get install -y ca-certificates curl gnupg lsb-release
    mkdir -p /etc/apt/keyrings
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor \
            -o /etc/apt/keyrings/docker.gpg
    
    echo "deb [arch=$(dpkg --print-architecture) \
        signed-by=/etc/apt/keyrings/docker.gpg] \
        https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | \
        sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

    apt-get update
    apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
}

test_docker()
{
    service docker start
    systemctl enable docker
    docker run hello-world
}

setup_non_root_run()
{
    GROUP_NAME=$1
    groupadd docker
    usermod -aG docker ${USER_NAME}
    newgrp docker
}

setup_selfboot()
{
    systemctl enable docker.service
    systemctl enable containerd.service
}

unsetup_selfboot()
{
    systemctl disable docker.service
    systemctl disable containerd.service
}

config_image_acceleration()
{
    mkdir -p /etc/docker
    cp ${SCRIPTS_DIR}/daemon.json /etc/docker

    systemctl daemon-reload
    systemctl restart docker
}

install_docker_compose()
{
    cp ${TOOLS_DIR}/docker-compose-linux-x86_64 /usr/local/bin/docker-compose
    chmod 777 /usr/local/bin/docker-compose
}

user_install_docker_image()
{
    UBUNTU_RELEASE=$1
    USER_UID=$(su ${USER_NAME} -c "id -u")
    USER_GID=$(su ${USER_NAME} -c "id -g")
    UID_LINE=$(grep -n "DEFAULT_UID" ${ROOT_DIR}/docker-compose.yml | cut -d ":" -f 1)
    GID_LINE=$(grep -n "DEFAULT_UID" ${ROOT_DIR}/docker-compose.yml | cut -d ":" -f 1)

    sed -r -i "s/(DEFAULT_UID: ).*/\1${USER_UID}/" ${ROOT_DIR}/docker-compose.yml
    sed -r -i "s/(DEFAULT_GID: ).*/\1${USER_GID}/" ${ROOT_DIR}/docker-compose.yml
    sed -r -i "s/(DEFAULT_USER: ).*/\1${USER_NAME}/" ${ROOT_DIR}/docker-compose.yml
    sed -r -i "s/(DEFAULT_PASSWD: ).*/\1${USER_PASSWD}/" ${ROOT_DIR}/docker-compose.yml
    sed -r -i 's/<user>/${USER_NAME}/g' docker-compose.yml

    if [ ${UBUNTU_RELEASE} == "Ubuntu1804"]; then
        sed -r -i 's/imagebuilderxxxx/imagebuilder1804/g' docker-compose.yml
        sed -r -i "s/(hostname: ).*/\1${UBUNTU_RELEASE}/" ${ROOT_DIR}/docker-compose.yml
        sed -r -i "s/(dockerfile: ).*/\1${UBUNTU_1804_IMAGE_BUILD_FILE}/" ${ROOT_DIR}/docker-compose.yml
        sed -r -i "s/(image: ).*/\1${UBUNTU_1804_IMAGE}/" ${ROOT_DIR}/docker-compose.yml
    fi

    su ${USER_NAME} -c "cd ${ROOT_DIR} && docker-compose up -d"
}

exit_scripts()
{
    sed -r -i 's/${USER_NAME}/<user>/g' docker-compose.yml
    if [ ${UBUNTU_RELEASE} == "Ubuntu1804"]; then
        sed -r -i 's/imagebuilder1804/imagebuilderxxxx/g' docker-compose.yml
        sed -r -i "s/(hostname: ).*/\1Ubuntuxxxx/" ${ROOT_DIR}/docker-compose.yml
        sed -r -i "s/(dockerfile: ).*/\1${UBUNTU_DEFAULT_IMAGE_BUILD_FILE}/" ${ROOT_DIR}/docker-compose.yml
        sed -r -i "s/(image: ).*/\1${UBUNTU_DEFAULT_IMAGE}/" ${ROOT_DIR}/docker-compose.yml
    fi
}

usage() {
    echo "Usage: sudo ./$PROGNAME -m <mode> -b <ubuntu_release> -p <passwd>"

    echo "    Optional parameters:
    * [-m mode]:                install or uninstall.
    * [-b ubuntu_release]:      Ubuntu1804 or Ubuntu2004, default is ubuntu2004.
    * [-u user_name]:           The username that needs to be configured into the Docker image 
    *                           should be consistent with the host username.
    * [-p passwd]:              Configure the password of the user who enters the Docker image
    * [-s acces]:               Whether to configure image acceleration, with values of true or false, default is false.
    * [-h]:                     help
"
}

# parse the parameters
OLD_OPTIND=$OPTIND
while getopts "u:p:s:m:b:" setup_flag
do
    case $setup_flag in
        # 要配置进 docker 组的用户名
        u) USER_NAME="$OPTARG";
           ;;
        # 要配置进 docer 组的用户名的密码
        p) USRE_PASSWD="$OPTARG";
           ;;
        # 配置镜像加速, true or false
        s) IMAGE_ACCEL="$OPTARG";
           ;;
        m) MODE="$OPTARG";
           ;;
        # 要安装的 ubuntu 的版本
        b) ubuntu_release="$OPTARG";
           ;;
        ?) usage;
           ;;
        h) usage;
           ;;
    esac
done
OPTIND=$OLD_OPTIND

if [ ! -z ${USER_NAME} ]; then
    if id -u ${USER_NAME} >/dev/null 2>&1 ; then
        echo "User ${USER_NAME} exists."
    else
        echo "User ${USER_NAME} does not exist!"
        exit 1
    fi
else
    USER_NAME=root
fi

if [ MODE == "unintstall" ]; then
    uninstall_software
    unsetup_selfboot
fi

uninstall_software

install_software

test_docker

setup_non_root_run

config_image_acceleration

install_docker_compose

user_install_docker_image ${ubuntu_release}